<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    button{
      position: fixed;
      right: 100px;
      bottom: 100px;
    }
  </style>
</head>
<body style="height: 3000px;">
  <div id="app">
    <button v-back-top="200" id="backTop">回到顶部</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    // 定义全局指令
    Vue.directive('back-top', {
      inserted(el, binding){
        // 初始化隐藏 回到顶部按钮
        el.style.display = 'none';
        // 添加滚动条事件 控制 按钮显示消失
        window.onscroll = () => {
          // 获取滚动举例
          const sTop = document.body.scrollTop || document.documentElement.scrollTop;
          if(sTop > binding.value) {
            // 显示按钮
            el.style.display = 'block';
          }else{
            el.style.display = 'none';
          }
        }
        // 添加点击事件回到顶部
        el.onclick = () => {
          window.scrollTo(0, 0);
        }
      },
      unbind(){
        window.onscroll = null;
      }
    })
    const vm = new Vue({
      el: '#app'
    })
  </script>
</body>
</html>